<template>
  <!-- 漏斗图组件 -->
  <div class="funnelChart" v-loading="loading">
    <div class="funnelChart-title">
      <span>{{ data.name }}</span>
    </div>
    <div class="funnelChart-date">
      <!-- 日期 -->
      <p v-if="screenTime && screenTime.length != 0">
        <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
      </p>
      <p v-else>
        <span v-if="data.relativelyTime || data.relativelyTime == 0" class="left">{{ relativelyTimeDeal.format("yyyy-MM-dd") }} ~ {{ new Date().format("yyyy-MM-dd") }}</span>
        <span v-else class="left">{{ new Date(data.startTime).format("yyyy-MM-dd") }} ~ {{ new Date(data.endTime).format("yyyy-MM-dd") }}</span>
      </p>
      <!-- el-tooltip -->
      <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
        <el-tooltip content="筛选时段" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
      </p>
      <p class="tooltip-p" v-else>
        <el-tooltip v-if="data.relativelyTime || data.relativelyTime == 0" :content="`统计时段 相对${ data.relativelyTime/3600/1000/24 == 0 ? '今' : data.relativelyTime/3600/1000/24 }天时段`" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
        <el-tooltip v-else content="统计时段 固定时段" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
      </p>
    </div>
    <!-- tabs -->
    <div class="funnelChart-tabs" v-if="multipleData && multipleData.length != 0">
      <el-radio-group v-model="radio" size="mini" @change="handleChangeRadio">
        <el-radio-button 
          :label="item.chnVal"
          v-for="(item, index) in multipleData"
          :key="index"
        ></el-radio-button>
      </el-radio-group>
      <!-- <el-button size="mini" plain style="height: 26px;">{{ multipleData[0].chnVal }}</el-button> -->
    </div>
    <div style="width: 100%;height: 34px;" v-else>
    </div>
    <!-- echarts -->
    <div v-if="payloadData.dayData && payloadData.dayData.length != 0 && isScreenComplete" :id="'funnelCharts' + id" class="funnelChart-echarts" style="width: 100%;height: 272px;"></div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import * as echarts from 'echarts';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  dataBoardByChartId,
  dataBoardMerchantGetChatData
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js'
export default {
  name: 'FunnelChart',
  components: {
    
  },
  props: {
    id: {
      type: Number,
      default: () => {
        return null;
      }
    }
  },
  data() {
    return {
      dateIcon,
      emptyImg,
      data: {},
      payloadData: {},
      multipleData: [],
      relativelyTimeDeal: null,
      loading: false,
      openDataScreenVisible: false,
      dataOptions: [],
      xAxisData: [],
      isScreenComplete: true
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.dataBoardMerchantGetChatDataApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
        this.dataBoardMerchantGetChatDataApi();
      },
      deep: true
    },
    openDataScreen: {
      handler(val) {
        if(val === this.id) {
          this.openDataScreenVisible = true
        }
      },
      deep: true
    }
  },
  mounted() {
    this.dataBoardByChartIdApi();
  },
  methods: {
    // 获取报表数据
    async dataBoardByChartIdApi() {
      let res = await dataBoardByChartId({
        id: this.id
      });
      if(res.code === 200) {
        this.data = res.payload;
        let start = new Date()
        start.setTime(start.getTime() - this.data.relativelyTime)
        this.relativelyTimeDeal = start;
        if(this.data.relativelyTime === 0) {
          this.relativelyTimeDeal = new Date();
        }
        // 获取chart数据
        this.dataBoardMerchantGetChatDataApi();
      }
    },
    // 获取报表具体数据
    async dataBoardMerchantGetChatDataApi() {
      this.loading = true;
      let startTime;
      let endTime;
      let screenTime = store.state.user.screenTime;
      if(screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      } else {
        // startTime 和 endTime存在即固定时间
        if(this.data.startTime && this.data.endTime) {
          startTime = this.data.startTime;
          endTime = this.data.endTime;
        }
        // relativelyTime存在即相对时间
        if(this.data.relativelyTime) {
          let nowDate = new Date().getTime();
          console.log(nowDate, '222');
          let startDate = nowDate - this.data.relativelyTime;
          startTime = startDate;
          endTime = nowDate;
        }
      }
      let res = await dataBoardMerchantGetChatData({
        id: this.id,
        startTime,
        endTime,
        insId: store.state.insId.insId
      })
      if(res.code === 200) {
        this.payloadData = res.payload;
        if(this.payloadData && this.payloadData.dayData.length != 0)  {
          this.capsulationDealData(0);
        } else {
          this.loading = false;
        }
      }
    },
    // 封装处理数据
    capsulationDealData() {
      let dataKeyName;
      let dataValueName;
      let seriesData = [];
      if(this.payloadData.groupColumn && this.payloadData.groupColumn.indexOf('columnHumpName') != -1) {
        // 分组
        let groupColumn = JSON.parse(this.payloadData.groupColumn.replace(/\\/g, ''));
        dataValueName = groupColumn[0].columnHumpName;
        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') === -1) {
          console.log('enter d z b ')
          // 单指标
          let specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=');
          this.chartName = specialColumn[1];
          this.payloadData.dayData.forEach(item => {
            let obj = {
              value: '',
              name: ''
            }
            obj.value = item.data;
            obj.name = item.groupColumn;
            seriesData.push(obj);
          })
        }
      }
      this.loading = false;
      this.$nextTick(() => {
        if(this.payloadData.dayData.length != 0) {
          console.log('seriesData ++++++', seriesData)
          let legendData = [];
          seriesData.forEach(item => {
            legendData.push(item.name);
          })
          this.drawCharts(legendData, seriesData);
        }
      })
    },
    drawCharts(legendData, seriesData) {
      let myChart = echarts.init(document.getElementById('funnelCharts' + this.id));
      let option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c}%'
        },
        legend: {
          data: legendData
        },
        series: [
          {
            name: 'Funnel',
            type: 'funnel',
            left: '25%',
            top: 60,
            bottom: 10,
            width: '50%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
              show: true,
              position: 'inside'
            },
            labelLine: {
              length: 10,
              lineStyle: {
                width: 1,
                type: 'solid'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1
            },
            emphasis: {
              label: {
                fontSize: 20
              }
            },
            data: seriesData
          }
        ]
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => {
        if(myChart) myChart.resize();
      })
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    },
    openDataScreen() {
      return store.state.user.openDataScreen;
    }
  }
}
</script>

<style lang="scss" scoped>
.funnelChart {
  width: 100%;
  height: 100%;
  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }
  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    // margin-bottom: 34px;
    .left {
      font-size: 12px;
      color: #6b798e;
    }
    .right {
      margin-left: 18px;
    }
    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  &-tabs {
    width: 100%;
    height: 34px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  &-echarts {
    width: 100%;
    height: 42px;
    
  }
}
</style>

<style lang="scss">
.funnelChart {
  .el-radio-button__inner {
    padding: 6px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}
</style>